import time
import random
from hashlib import md5
from datetime import datetime


class Tools:
    @staticmethod
    def md5_hash(text: str):
        """ 计算给定字符串的 md5 值

            `text` 字符串
        """
        hash_object = md5(text.encode("utf-8"), usedforsecurity=False)

        return hash_object.hexdigest()

    @staticmethod
    def date_to_timestamp(date_str: str, formatString='%Y-%m-%d'):
        # 将日期字符串转换为 datetime 对象
        date_obj = datetime.strptime(date_str, formatString)
        # 将 datetime 对象转换为时间戳
        timestamp = time.mktime(date_obj.timetuple())

        return timestamp

    @staticmethod
    def generate_code(type='default', length=5):
        """ 生成随机字符序列

            `type` `random` 随机数字+随机大小字母 `letter` 随机大小字母 `default` 随机数字

            `length` 码长度 默认 5 位
        """

        letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        digits = '0123456789'

        if type == 'random':
            salt = letters + digits
        elif type == 'letter':
            salt = letters
        else:
            salt = digits

        code = ''
        for i in range(length):
            code += random.choice(salt)

        return code
